﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using System.IO;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using Microsoft.SharePoint.Utilities;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Web;

/*
Developed By: Niraj Kumar Rai
Developed On: 8th Aug 2011
Description: This code Create site on user login
*/
namespace CreatePersonalSite.Create_Personal_Site
{
    public partial class Create_Personal_SiteUserControl : UserControl
    {
        string siteName, workEmail, fullName, userName, accountName, accountName1, siteUrl;


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if ((siteExists()) || (fullName == "System Account"))
                {
                    //If personal is exist in site collection then redirect to site default page                 
                    Response.Redirect(SPContext.Current.Site.Url + "/default.aspx", false);
                }

            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnCreateSite_Click(object sender, ImageClickEventArgs e)
        {
            //Check is Site Exist or not
            siteUrl = SPContext.Current.Site.Url + "/default.aspx";
            if ((siteExists()) || (fullName == "System Account"))
            {   //If personal is exist in site collection then redirect to site default page
                Response.Redirect(SPContext.Current.Site.Url + "/default.aspx", false);
            }
            else
            {
                //Call the create personal site method
                           
                CreatePersonalSite();
             
            }
        }

        /// <summary>
        /// Check login user personal site is exist in site collection
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        public bool siteExists()
        {
            FindUserInfo();
            bool IsExist = false;
            string personalSite = "personal/" + siteName;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
                SPSiteCollection siteCollections = webApplication.Sites;

                for (int i = 0; i < siteCollections.Count; i++)
                {
                    //Check site name is exist in collection                   
                    if (personalSite == siteCollections.Names[i].Trim())
                    {
                        //if site exist then return true value
                        IsExist = true;
                    }
                }
            });
            return IsExist;
        }

        /// <summary>
        /// Find the login user information and current login site information
        /// </summary>
        public void FindUserInfo()
        {
            SPWeb web = SPControl.GetContextWeb(Context);
            SPUser sUser = web.CurrentUser;


            string userName1 = this.Context.User.Identity.Name;

            //userName = sUser.LoginName;
            //accountName = userName;
            accountName1 = sUser.LoginName;
            //fullName = sUser.Name;
            //workEmail = sUser.Email;

            userName = this.Context.User.Identity.Name;
            accountName = this.Context.User.Identity.Name;
            fullName = this.Context.User.Identity.Name;
            workEmail = sUser.Email;


            //Condition check to fetch the junk value in the sharepoint variable.
            if (userName.ToString().Contains("f|sqlmember|"))
            {
                string indexUser = userName.ToString().Substring(userName.ToString().LastIndexOf('|'));
                userName = indexUser.Trim('|').Trim().ToString();
            }

            //userName = userName.Replace("i:0#.w|", "");
            int pos = userName.IndexOf("\\");
            if (pos > 0)
                userName = userName.Substring(pos + 1);

            siteName = userName.Replace(".", "_");
            siteName = siteName.Replace("@", "_");

            if (accountName.ToString().Contains("f|sqlmember|") || accountName.ToString().Contains("0#.w|") || accountName.ToString().Contains("i:0#.w|"))
            {
                string indexUser = accountName.ToString().Substring(accountName.ToString().LastIndexOf('|'));
                accountName = indexUser.Trim('|').Trim().ToString();
            }

        }

        /// <summary>
        /// Update the personal site properties  in user profile.
        /// </summary>
        public void UpdateUserProfile()
        {
            try
            {

                SPWeb objweb = SPContext.Current.Web;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    // SPWeb ojweb  = SPControl.GetContextWeb(Context);
                    SPUser sUser = objweb.CurrentUser;

                    //Update the personal site properties  in user profile.

                    using (SPSite site = new SPSite(objweb.Site.Url))
                    {
                        site.AllowUnsafeUpdates = true;

                        using (SPWeb oweb = site.RootWeb)
                        {
                            oweb.AllowUnsafeUpdates = true;
                            SPServiceContext context = SPServiceContext.GetContext(site);
                            UserProfileManager profileManager = new UserProfileManager(context);
                            UserProfile profileUser = profileManager.GetUserProfile(accountName);
                            // UserProfile profileUser = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
                            // profileUser[PropertyConstants.PersonalSpace].ProfileSubtypeProperty.IsUserEditable = true;
                            profileUser[PropertyConstants.PersonalSpace].Value = "/personal/" + siteName;
                            profileUser.Commit();
                        }
                    }
                });
                Response.Redirect(SPContext.Current.Site.Url + "/default.aspx", false);
            }
            catch (Exception e)
            {
                lblMsg.Text = e.Message;
            }
            // Response.Redirect(siteUrl, true);
        }

        /// <summary>
        /// Create the login user personal site
        /// </summary>
        protected void CreatePersonalSite()
        {
            if (siteName.Length > 0)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H3>Creating personal site</H3></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait while your personal site is setup for the first time and the document libraries and lists are created. This may take several seconds.</H5></DIV>";
                    lop.Begin();
                     try
                     {
                         SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                         using (SPSite site = webApp.Sites.Add("/personal/" + siteName, "MySite", null, 1033, null, userName, userName, workEmail))
                         {
                             SPWeb rootWeb = site.RootWeb;

                             //Get Solutions Gallery    
                             SPDocumentLibrary solutions = (SPDocumentLibrary)site.GetCatalog(SPListTemplateType.SolutionCatalog);

                             //Upload Solution File with the Web Template                         
                             SPFile solutionFile = solutions.RootFolder.Files.Add("LaTrobeMyContentV3.wsp",
                             File.ReadAllBytes(Server.MapPath("/_layouts/CreatePersonalSite/LaTrobeMyContentV3.wsp")));

                             // Activate Solution    
                             SPUserSolution solution = site.Solutions.Add(solutionFile.Item.ID);

                             // Activate Features    
                             Guid solutionId = solution.SolutionId;

                             // Activate Site Collection Features    
                             SPFeatureDefinitionCollection siteFeatures = site.FeatureDefinitions;
                             var features = from SPFeatureDefinition f in siteFeatures
                                            where f.SolutionId.Equals(solutionId)
                                            && f.Scope == SPFeatureScope.Site
                                            select f;
                             foreach (SPFeatureDefinition feature in features)
                             {
                                 site.Features.Add(feature.Id, false, SPFeatureDefinitionScope.Site);
                             }

                             // Get Web Template    
                             SPWebTemplateCollection webTemplates = site.RootWeb.GetAvailableWebTemplates(1033);
                             SPWebTemplate webTemplate = (from SPWebTemplate t in webTemplates
                                                          where t.Title == "LaTrobeMyContentV3"
                                                          select t).FirstOrDefault();
                             if (webTemplate != null)
                             {
                                 site.RootWeb.ApplyWebTemplate(webTemplate.Name);
                             }


                             //objSite.RootWeb.CreateDefaultAssociatedGroups(ownerLogin, secondaryContactLogin, SiteName);
                             site.RootWeb.CreateDefaultAssociatedGroups(accountName1, accountName1, userName);
                             UpdateUserProfile();
                             GrantPermissions(rootWeb);
                         }
                     }
                     catch (Exception)
                     {
                         lblMsg.Text = "Your personal site has not been created successfully, please contact your RIC administrator.";
                     }
                     lop.End(SPContext.Current.Site.Url + "/default.aspx", Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                 });
                Response.Redirect(SPContext.Current.Site.Url + "/default.aspx", false);
            }

        }

        /// <summary>
        /// Grant the permissions to users
        /// </summary>
        /// <param name="web"></param>
        protected void GrantPermissions(SPWeb web)
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser allUser = web.EnsureUser("All Authenticated Users");
                SPRoleDefinition roleDefinition = web.RoleDefinitions["Read"];
                SPRoleAssignment roleAssignment = new SPRoleAssignment(allUser);
                roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                web.RoleAssignments.Add(roleAssignment);
            }
            catch { }
        }
    }
}